use std::io;
use std::fs::File;
use reqwest::{blocking::Client, Error as ReqwestError, StatusCode};
use thiserror::Error;
use htmd::HtmlToMarkdown;

#[derive(Debug, Error)]
pub enum ScreenshotError {
    #[error("HTML to Markdown conversion error: {0}")]
    IoError(#[from] io::Error),
    
    #[error("HTTP request error: {0}")]
    RequestError(#[from] ReqwestError),
    
    #[error("HTTP status error: {0}")]
    StatusError(StatusCode),
}

pub fn screenshot(url: &str, output_path: &str) -> Result<(), ScreenshotError> {
    // 设置API参数
    let customer_key = "2536f8"; // 需要替换为实际的API密钥
    let dimension = "1366xfull";
    let device = "desktop";
    let format = "png";
    let cache_limit = "0";
    let delay = "2000";
    let zoom = "100";
    
    // 创建HTTP客户端
    let client = Client::new();
    let request = client.get("https://api.screenshotmachine.com")
        .query(&[("key", customer_key)])
        .query(&[("url", url)])
        .query(&[("dimension", dimension)])
        .query(&[("device", device)])
        .query(&[("format", format)])
        .query(&[("cacheLimit", cache_limit)])
        .query(&[("delay", delay)])
        .query(&[("zoom", zoom)]);
    
    // 发送请求并获取响应
    let response = request.send()?;
    
    // 检查响应状态
    if !response.status().is_success() {
        return Err(ScreenshotError::StatusError(response.status()));
    }
    
    // 将响应内容保存到文件
    let mut file = File::create(output_path)?;
    let bytes = response.bytes()?;
    io::copy(&mut bytes.as_ref(), &mut file)?;
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_screenshot() -> Result<(), ScreenshotError> {
        let test_url = "https://cisco.github.io/ChezScheme/csug/use.html#./use:h0";
        let output_path = "/data/test/test_screenshot.png"; // 保存到当前目录
        
        println!("正在生成截图: {}", output_path);
        screenshot(test_url, output_path)?;
        
        // 验证文件是否存在
        let metadata = std::fs::metadata(output_path)?;
        assert!(metadata.is_file());
        assert!(metadata.len() > 0);
        
        println!("截图已保存到: {}", std::fs::canonicalize(output_path)?.display());
        
        // 不再删除测试文件，让用户可以查看
        // std::fs::remove_file(output_path)?;
        
        Ok(())
    }
}